package com.love.cloud.admin.api.provider;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.love.cloud.admin.api.dto.ManagerDTO;
import com.love.cloud.admin.api.dto.UserInfo;
import com.love.cloud.admin.api.entity.*;
import com.love.cloud.admin.api.vo.UserVO;
import com.love.cloud.admin.mapper.SysDeptMapper;
import com.love.cloud.admin.mapper.SysRoleMapper;
import com.love.cloud.admin.mapper.SysUserDeptMapper;
import com.love.cloud.admin.mapper.SysUserRoleMapper;
import com.love.cloud.admin.service.DingTalkService;
import com.love.cloud.admin.service.SysDeptService;
import com.love.cloud.admin.service.SysUserService;
import com.love.cloud.common.zzd.api.GovDingAPICaller;
import com.love.cloud.common.zzd.dto.DingOrgPathDto;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author hongdongqu
 */
@DubboService(version = "1.0.0",timeout = 30000)
public class RemoteUserServiceProvider implements RemoteUserProvider{
    private final Logger logger = LoggerFactory.getLogger(RemoteUserServiceProvider.class);
    @Resource
    private SysUserService userService;
    @Resource
    private DingTalkService dingTalkService;
    @Resource
    private SysUserDeptMapper sysUserDeptMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private SysDeptService sysDeptService;
    @Resource
    private GovDingAPICaller govDingAPICaller;

    @Override
    public UserInfo userInfoById(String userId) {
        SysUser user = userService.getById(userId);
        if (user == null) {
            return null;
        }
        return userService.getUserInfo(user);
    }

    @Override
    public UserInfo info(String username) {
        SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username));
        if (user == null) {
            return null;
        }
        return userService.getUserInfo(user);
    }

    @Override
    public UserInfo infoByPhone(String phone) {
        SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getMobile, phone));
        if (user == null) {
            return null;
        }
        return userService.getUserInfo(user);
    }

    @Override
    public UserInfo infoByZZDQRCode(String QRCode,boolean autoAdd) {
        SysUser sysUser = dingTalkService.parseZZDingQrCode(QRCode,autoAdd);
        if(sysUser==null){
            return null;
        }
        return userService.getUserInfo(sysUser);
    }

    @Override
    public UserInfo infoByZZDingFreeLogin(String authCode) {
        SysUser sysUser = dingTalkService.ZZDingFreeLogin(authCode);
        if(sysUser==null){
            return null;
        }
        return userService.getUserInfo(sysUser);
    }

    @Override
    public UserInfo infoByAccountId(String accountId) {
        SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getZDingAccountId, accountId));
        if (user == null) {
            return null;
        }
        return userService.getUserInfo(user);
    }

    @Override
    public SysUser getUser(String userId) {
//        logger.info("获取用户:{}", SecurityUtils.getUser().getId());
        return userService.getById(userId);
    }

    @Override
    public List<SysDept> getDeptInfoByDingOrgCodes(Set<String> dingOrgCodeSet) {
        QueryWrapper<SysDept> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().in(SysDept::getDingTalkId,dingOrgCodeSet);
        List<SysDept> sysDeptList = sysDeptMapper.selectList(queryWrapper);
        return sysDeptList;
    }

    @Override
    public List<UserInfo> getUserInfoListByDeptOrRoleCode(List<Long> deptIdList, String roleCode) {
        List<UserInfo> userInfoList=new ArrayList<>();
        //用户集合
        Set<Long> userIdsSet=new HashSet<>();
        //通过角色标识来获取到对应的角色信息
        QueryWrapper<SysRole> roleQueryWrapper=new QueryWrapper<>();
        roleQueryWrapper.lambda().eq(SysRole::getRoleCode,roleCode).last(" limit 1");
        SysRole sysRole = sysRoleMapper.selectOne(roleQueryWrapper);
        if(sysRole!=null){
            QueryWrapper<SysUserRole> userRoleQueryWrapper=new QueryWrapper<>();
            userRoleQueryWrapper.lambda().eq(SysUserRole::getRoleId,sysRole.getRoleId());
            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(userRoleQueryWrapper);
            //获取到角色用户id集合
            Set<Long> roleUserIdsSet = sysUserRoles.stream().map(SysUserRole::getUserId).collect(Collectors.toSet());
            //获取到对应的角色的用户id
            QueryWrapper<SysUserDept> userDeptQueryWrapper=new QueryWrapper<>();
            userDeptQueryWrapper.lambda().in(SysUserDept::getDeptId,deptIdList);
            List<SysUserDept> sysUserDeptList = sysUserDeptMapper.selectList(userDeptQueryWrapper);
            //获取到部门用户id集合
            Set<Long> deptUserIdsSet = sysUserDeptList.stream().map(SysUserDept::getUserId).collect(Collectors.toSet());
            //获取两个集合的交集
            userIdsSet.addAll(roleUserIdsSet);
            userIdsSet.retainAll(deptUserIdsSet);
            if(userIdsSet!=null&&userIdsSet.size()>0){
                //获取到具体的用户基本信息
                QueryWrapper<SysUser> sysUserQueryWrapper=new QueryWrapper<>();
                sysUserQueryWrapper.lambda().in(SysUser::getId,userIdsSet);
                List<SysUser> list = userService.list(sysUserQueryWrapper);
                //加载用户对应的角色和部门还有权限
                for (SysUser sysUser :list) {
                    UserInfo userInfo = userService.getUserInfo(sysUser);
                    userInfoList.add(userInfo);
                }
            }
        }
        return userInfoList;
    }

    @Override
    public Page<UserInfo> getUserInfoListByDeptOrRoleCodeAndNamePage(Page<UserInfo> page,List<String> deptNameList, String roleCode, String name) {
        //用户集合
        Set<Long> userIdsSet=new HashSet<>();
        //通过角色标识来获取到对应的角色信息
        QueryWrapper<SysRole> roleQueryWrapper=new QueryWrapper<>();
        roleQueryWrapper.lambda().eq(SysRole::getRoleCode,roleCode).last(" limit 1");
        SysRole sysRole = sysRoleMapper.selectOne(roleQueryWrapper);
        if(sysRole!=null){
            QueryWrapper<SysUserRole> userRoleQueryWrapper=new QueryWrapper<>();
            userRoleQueryWrapper.lambda().eq(SysUserRole::getRoleId,sysRole.getRoleId());
            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(userRoleQueryWrapper);
            //获取到角色用户id集合
            Set<Long> roleUserIdsSet = sysUserRoles.stream().map(SysUserRole::getUserId).collect(Collectors.toSet());
            //添加
            userIdsSet.addAll(roleUserIdsSet);
            if(deptNameList!=null&&deptNameList.size()>0){
                //获取到对应的部门信息
                QueryWrapper<SysDept> deptQueryWrapper=new QueryWrapper<>();
                deptQueryWrapper.lambda().select(SysDept::getId)
                        .in(SysDept::getName,deptNameList);
                List<SysDept> sysDeptList = sysDeptMapper.selectList(deptQueryWrapper);
                //获取到部门id
                Set<Long> deptIdSet = sysDeptList.stream().map(SysDept::getId).collect(Collectors.toSet());
                if(deptIdSet!=null&&deptIdSet.size()>0){
                    QueryWrapper<SysUserDept> userDeptQueryWrapper=new QueryWrapper<>();
                    userDeptQueryWrapper.lambda().in(SysUserDept::getDeptId,deptIdSet);
                    List<SysUserDept> sysUserDeptList = sysUserDeptMapper.selectList(userDeptQueryWrapper);
                    //获取到部门用户id集合
                    Set<Long> deptUserIdsSet = sysUserDeptList.stream().map(SysUserDept::getUserId).collect(Collectors.toSet());
                    //获取集合的交集
                    userIdsSet.retainAll(deptUserIdsSet);
                }else{
                    return page;
                }
            }
            if(userIdsSet!=null&&userIdsSet.size()>0){
                Page<SysUser> userPage=new Page<>();
                BeanUtils.copyProperties(page,userPage);
                //获取到具体的用户基本信息
                QueryWrapper<SysUser> sysUserQueryWrapper=new QueryWrapper<>();
                sysUserQueryWrapper.lambda().in(SysUser::getId,userIdsSet)
                        .like(StringUtils.isNotEmpty(name),SysUser::getName,name);
                //获取到分页数据
                userService.page(userPage,sysUserQueryWrapper);
                List<UserInfo> userInfoList=new ArrayList<>();
                //加载用户对应的角色和部门还有权限
                for (SysUser sysUser :userPage.getRecords()) {
                    UserInfo userInfo = userService.getUserInfo(sysUser);
                    userInfoList.add(userInfo);
                }
                page.setTotal(userPage.getTotal());
                //塞到分页的对象中
                page.setRecords(userInfoList);
            }
        }
        return page;
    }

    @Override
    public List<UserVO> getUserListDeptId(Long deptId) {
        return userService.getUserListDeptId(deptId);
    }

    @Override
    public SysDept getDeptById(Long deptId) {
        return sysDeptMapper.selectById(deptId);
    }

    @Override
    public boolean updateOpenCodeByUserId(Long userId,String openCode) {
        return  userService.updateOpenCodeByUserId(userId,openCode);
    }

    @Override
    public List<SysUser> getUsers(List<String> ids) {
        return userService.listByIds(ids);
    }
}
